
package com.tg.base.concurrent.thread;

import java.util.concurrent.TimeUnit;

public class ThreadInterruptedTest {

    public static void main(String[] args) {
//        test2();

        whenWithValidateIsInterrupted();

//        whenWithoutValidateIsInterrupted();

//        whenSleep();
    }

    private static void whenValidateIsInterrupted() {
        Thread thread = new Thread(() -> {
            while (true) {
                Thread.yield();

                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("中断退出");
                    return;
                }
            }
        });

        thread.start();
        thread.interrupt();
    }

    /**
     * 线程内部有处理中断时，则可以中断
     * output：中断退出
     */
    private static void whenWithValidateIsInterrupted() {
        Thread thread = new Thread(() -> {
            int i = 100000;
            while (i > 0) {
                if (Thread.currentThread().isInterrupted()) {
                    System.out.println("中断退出");
                    return;
                }

                i -= 1;
            }
            System.out.println("完成全部计算");
        });

        thread.start();
        thread.interrupt();
    }

    /**
     * 线程内部没有处理中断时，则不能中断
     * output：完成全部计算
     */
    private static void whenWithoutValidateIsInterrupted() {
        Thread thread = new Thread(() -> {
            int i = 100000;
            while (i > 0) {
                i -= 1;
            }
            System.out.println("完成全部计算");
        });

        thread.start();
        thread.interrupt();
    }

    /**
     * thread.sleep()进入TIMED_WAITING状态
     * 当外部中断线程，抛出InterruptedException
     */
    private static void whenSleep() {
        Thread thread = new Thread(() -> {
            try {
                TimeUnit.MILLISECONDS.wait(200);
            } catch (InterruptedException ex) {
                System.out.println("sleep捕捉InterruptedException");
            }
        });

        thread.start();
        thread.interrupt();
    }

    private static Integer target = 1;

//    /**
//     * 当synchronized阻塞
//     */
//    private static void whenSyncBlock() {
//         new Thread(() -> {
//            synchronized (target) {
//                try {
//                    target += 1;
//                    TimeUnit.MILLISECONDS.sleep(100);
//                } catch (InterruptedException e) {
//                    e.printStackTrace();
//                }
//            }
//        }).start();
//
//        Thread thread2 = new Thread(() -> {
//            synchronized (target) {
//               if(Thread.currentThread().isInterrupted()){
//                   return;
//               }
//            }
//        });
//
//        thread2.start();
//        thread.interrupt();
//    }
}